<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Models\CzHookChannel;
use App\Models\CzHookSpec;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class CzHookSpecController extends ApiBaseController
{

    public function index(Request $request){
        $paginator = CzHookSpec::with(['spec', 'channels', 'spec.product','channels.channel','province','city'])->filter($request->all())->paginate($this->pageSize);
        return success(page_format($paginator));
    }

    public function show(Request $request, CzHookSpec $model){
        $id = $request->get('id');
        $data = $model->with(['product', 'spec','channels.channel'])->find($id);
        return success(['data' => $data->toArray()]);
    }

    public function add(Request $request){
        $params = $request->all();

        DB::transaction(function () use ($params) {
            $model = CzHookSpec::updateOrCreate(
                [
                    'spec_id' => intval($params['spec_id']),
                    'province_id' => intval($params['province_id']),
                    'city_id' => intval($params['city_id']),
                ],
                [
                    'condit' => intval($params['condit']),
                    'act' => intval($params['act']),
                    'is_loop' =>  $params['is_loop'] ?? 0,
                    'sort_type' => $params['sort_type'] ?? 1,
                    'status' =>  $params['status'] ?? 0,
                ]
            );
            $channels = $params['channels'];
            if($params['act'] == 3 && count($channels) == 0){
                throw new HttpResponseException(error('请选择渠道产品'));
            }

            if(count($channels) > 0){
                foreach ($channels as $channel){
                    CzHookChannel::where('hook_id',$model->id)->delete();
                    $tmp_add = [
                        'channel_product_id' => intval($channel['channel_product_id']),
                        'channel_id' => intval($channel['channel_id']),
                        'submit_nums' => intval($channel['submit_nums']),
                        'sort' => intval($channel['sort']),
                        'hook_id' => $model->id,
                    ];
                    CzHookChannel::create($tmp_add);
                }
            }
        });
        return success([],'添加成功');

    }

    public function destroy($ids, Request $request, CzHookSpec $model){
        $id_arr = explode(',', $ids);
        DB::transaction(function () use ($id_arr, $model) {
            $model->destroy($id_arr);
            DB::table('cz_hook_channel')->whereIn('hook_id', $id_arr)->delete();
        });

    }
}
